const app = getApp();

let api = require('../../utils/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentIndex: 0,
    "firstList": [],
    "secondList": [],
    "thirdList": [],
    "fourthList": [],
    "fifthList": [],
    "firstListTotal": Number,
    "secondListTotal": Number,
    "thirdListTotal": Number,
    "fourthListTotal": Number,
    "fifthListTotal": Number,
    pageNum: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    app.getRemind()
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight - app.globalData.navHeight,
          listHeight: ((res.windowHeight - app.globalData.navHeight) * 2 - 88) / 2
          // listHeight: res.windowHeight - app.globalData.navHeight  - 44
        });
      }
    });

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;

    var state = [],
      total = [],
      name = [];
    state = [0, 2, 3, 4];
    total = ['firstListTotal', 'secondListTotal', 'thirdListTotal', 'fourthListTotal'];
    name = ['firstList', 'secondList', 'thirdList', 'fourthList'];
    var token = wx.getStorageSync('TOKEN')

    var param = {
      state: state[that.data.currentIndex],
      pageNum: 1,
      pageSize: 5
    };
    that.orderTotal(token);
    that.getOrderList(state[that.data.currentIndex], param, wx.getStorageSync('TOKEN'), total[that.data.currentIndex], name[that.data.currentIndex]);
  },
  //用户点击tab时调用
  titleClick: function (e) {
    var that = this;
    let currentPageIndex =
      that.setData({
        //拿到当前索引并动态改变
        currentIndex: e.currentTarget.dataset.idx
      })
    var item = e.currentTarget.dataset.total;
    var dataList = e.currentTarget.dataset.listname;
    var param = {
      state: e.currentTarget.dataset.state,
      pageNum: 1,
      pageSize: 5
    };
    that.setData({
      pageNum: 1
    })
    var token = wx.getStorageSync('TOKEN')
    that.getOrderList(e.currentTarget.dataset.state, param, token, item, dataList);
    that.orderTotal(token)
  },
  // 禁止用户左右滑动
  catchTouchMove: function (res) {
    return false
  },
  // 订单详情
  openDetail: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.gid;
    console.log(id);
    wx.navigateTo({
      url: 'orderDetail/orderDetail?id=' + id
    })
  },
  // 获取订单列表
  getOrderList: function (idx, param, token, item, dataList, loadMore) {
    var that = this;
    var stateData = [];
    stateData[0] = '待接货';
    stateData[1] = '已接单';
    stateData[2] = '已装货';
    stateData[3] = '待发货';
    stateData[4] = '送货中';
    stateData[5] = '已达到';
    stateData[6] = '待评价';
    api._get('/omc/order/list/' + idx, param, token).then(res => {
      if (res.code == 200) {
        var list = res.result;

        list.forEach(function (value, index) {
          var createTime = value.createTime * 1000;
          var shipmentTime = value.shipmentTime.end * 1000;
          list[index]['createTime'] = app.formatDate(createTime, 'YYYY-MM-DD')
          list[index]['showShipmentTime'] = app.formatDate(shipmentTime, 'YYYY-MM-DD');
          if (value.state < 0) {
            list[index]['showState'] = '取消中';
          } else {
            if (value.state == 6) {
              if (value.isEvaluate == 0) {
                list[index]['showState'] = '待评价';
              } else {
                list[index]['showState'] = '已评价';
              }
            } else {
              list[index]['showState'] = stateData[list[index]['state']];
            }
          }
          if (value.freightWeight.max && value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.min + '-' + value.freightWeight.max + '吨';
          } else if (value.freightWeight.max && !value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.max + '吨';
          } else if (!value.freightWeight.max && value.freightWeight.min) {
            list[index]["showfreightWeight"] = value.freightWeight.min + '吨';
          }
        });
        if (loadMore) {
          console.log(param.pageNum)
          console.log(res.page.totalPage)
          if (param.pageNum <= res.page.totalPage) {

            var showData = [...that.data[dataList], ...list];
            console.log(showData)
            that.setData({
              [dataList]: showData
            })
          } else {
            wx.showToast({
              title: '没有更多订单',
              icon: 'none',
            })
            return false
          }
        } else {
          that.setData({
            // [item]: res.page.totalRow,
            [dataList]: list
          })
        }

      } else if (res.code > 400) {
        wx.navigateTo({
          url: '../login/login',
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }

    })
  },
  // 打电话
  callExpert: function (e) {
    // console.log(e.currentTarget.dataset.phone)
    var phone = e.currentTarget.dataset.phone;
    app.callExpert();
  },
  // 获取订单统计数
  orderTotal: function (token) {
    var that = this;
    api._get('/omc/order/total', '', token).then(res => {
      // console.log(res.code)
      if (res.code == 200) {
        that.setData({
          firstListTotal: res.result.awaitReceiveTotal,
          secondListTotal: res.result.awaitShipmentsTotal,
          // secondListTotal: res.result.haveOrderTotal,
          thirdListTotal: res.result.awaitReceiptTotal,
          fourthListTotal: res.result.awaitEvaluate,
        })

      } else if (res.code > 400) {
        wx.navigateTo({
          url: '../login/login',
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }
    })
  },

  /**
   * 订单操作
   */
  orderAction: function (e) {
    var that = this;
    // console.log(e.currentTarget.dataset.orderid);
    var countent = '';

    var state1 = [],
      total = [],
      name = [];
    state1 = [0, 2, 3, 4];
    total = ['firstListTotal', 'secondListTotal', 'thirdListTotal', 'fourthListTotal'];
    name = ['firstList', 'secondList', 'thirdList', 'fourthList'];
    // var state=[0,2,3,4];
    // var listName=['firstList','secondList','thirdList','fourthList']
    var state = e.currentTarget.dataset.state;
    console.log(e.currentTarget.dataset.orderid);
    if (state == 12) {
      countent = '确认收货前，请确认已收到货物，并检查货物是否完好。点击确定后，默认订单已完成。'
      wx.navigateTo({
        url: './pay/index?orderid=' + e.currentTarget.dataset.orderid + '&money=' + e.currentTarget.dataset.money,
      })
    } else {
      if (state == 2) {
        countent = '确认申请取消订单。点击确定后，申请将推送到司机端，待司机确认。'
      } else if (state == 1) {
        countent = '确认取消订单。点击确定后，订单将被取消。'
      }

      wx.showModal({
        content: countent,
        success: function (res) {
          if (res.confirm) {
            var token = wx.getStorageSync('TOKEN');
            var params = {
              id: e.currentTarget.dataset.orderid,
              state: parseInt(e.currentTarget.dataset.state),
              token: token
            }
            app.orderAction(params).then(function (code) {
              if (code == 200) {
                that.orderTotal(token)
                var param = {
                  state: state1[that.data.currentIndex],
                  pageNum: 1,
                  pageSize: 5
                };
                that.getOrderList(state1[that.data.currentIndex], param, token, total[that.data.currentIndex], name[that.data.currentIndex])
              } else if (res.cancel) {}
            })
          }

        }
      })

    }
  },
  onRefresh: function (e) {
    var callback = e.detail;
    var that = this;
    // console.log(e);
    var state = [],
      total = [],
      name = [];
    state = [0, 2, 3, 4];
    total = ['firstListTotal', 'secondListTotal', 'thirdListTotal', 'fourthListTotal'];
    name = ['firstList', 'secondList', 'thirdList', 'fourthList'];
    var param = {
      state: state[that.data.currentIndex],
      pageNum: 1,
      pageSize: 5
    };

    that.setData({
      pageNum: 1
    })
    setTimeout(function () {
      that.getOrderList(state[that.data.currentIndex], param, wx.getStorageSync('TOKEN'), total[that.data.currentIndex], name[that.data.currentIndex]);
      that.orderTotal(wx.getStorageSync('TOKEN'))
      callback.success();
    }, 3000)
  },
  onLoadMore: function (e) {
    var callback = e.detail;

    var that = this;
    // console.log(e);
    var state = [],
      total = [],
      name = [];
    state = [0, 2, 3, 4];
    total = ['firstListTotal', 'secondListTotal', 'thirdListTotal', 'fourthListTotal'];
    name = ['firstList', 'secondList', 'thirdList', 'fourthList'];
    var param = {
      state: state[that.data.currentIndex],
      pageNum: that.data.pageNum + 1,
      pageSize: 5
    };
    that.setData({
      pageNum: that.data.pageNum + 1
    })
    setTimeout(function () {
      that.getOrderList(state[that.data.currentIndex], param, wx.getStorageSync('TOKEN'), total[that.data.currentIndex], name[that.data.currentIndex], true);
      that.orderTotal(wx.getStorageSync('TOKEN'))
      callback.success();
    }, 3000)
  },

  /**
   * 去评价
   */
  evaluate: function (e) {
    // console.log(e.currentTarget.dataset.orderid);
    var id = e.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: 'evaluate/index?id=' + id
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res);
    if (res.from === 'button') {
      console.log('来自页面内转发按钮');
      wx.switchTab({
        url: '/pages/index/index'
      })
      this.setData({
        showShareModelStatus: false
      })
    } else if (res.from === 'menu') {
      console.log(res.from);
      console.log('右上角菜单转发按钮');
    }
  }
})